package com.lizemin;

import com.lizemin.entity.Account;
import com.lizemin.entity.Course;
import com.lizemin.entity.IdCard;
import com.lizemin.entity.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class AnnotationTest3 {

    Session session = null;
    Transaction tx = null;

    @Before
    public void init(){
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml") // configures settings from hibernate.cfg.xml
                .build();
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata()
                .buildSessionFactory();
        //创建SQL session连接
        session = sessionFactory.openSession();
        //开启事务
        tx = session.beginTransaction();
    }

    @After
    public void closeConnection() {
        if (null != session && session.isOpen()){
            //关闭session
            session.close();
        }
    }
    
    @Test
    public void test1(){
        Person person = new Person();
        person.setName("李四");

        IdCard idCard = new IdCard();
        idCard.setCode("20210808");

        person.setIdCard(idCard);
        idCard.setPerson(person);

        session.save(person);
        session.save(idCard);

        tx.commit();
    }

    
}
